<template>
  <el-drawer
    v-model="visible"
    :title="title"
    size="820px"
    class="order-drawer"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :validate-on-rule-change="false"
      label-width="80px"
      class="order-form"
    >
      <div class="section-title" v-if="addType === 'superaddition'">
        <span class="label">原始单号</span>
        <el-form-item label="" label-width="0" style="margin-bottom: 0">
          <div class="recognize-row">
            <el-input
              readonly
              class="ocr-input"
              v-model="form.relatedOrderId"
              placeholder="请选择或输入单号"
            >
              <template #suffix>
                <el-button type="primary" link @click="orderDialogRef?.show" :icon="Search">
                  选择订单
                </el-button>
              </template>
            </el-input>
          </div>
          <el-alert type="success" style="margin-top: 5px; padding: 1px 10px" :closable="false">
            <!-- 追加订单 是把 平台的某一个订单
            当作定金，在复购单补全对应的产品进行发货（需要同步物流单号到平台即可）
            注意：平台转定金，自动带出已付金额，但可以修改 -->
            将平台订单作为定金，复购时补全尾款及产品并发货，同步物流单号回传平台。
          </el-alert>
        </el-form-item>
      </div>
      <!-- 识别输入 -->
      <div class="section-title">
        <span class="label">基础信息</span>

        <span class="label collapse-btn">
          <el-button text size="small" @click="toggleCollapse">
            <el-icon>
              <component :is="isCollapsed ? ArrowUp : ArrowDown" />
            </el-icon>
            <span> {{ isCollapsed ? '收起' : '展开' }}</span>
          </el-button>
        </span>
        <template v-if="!isCollapsed">
          <CollapsedCustom :form="form" />
        </template>
        <template v-else>
          <!-- <el-form-item label="" label-width="0">
            <div class="recognize-row">
              <el-input
                class="ocr-input"
                v-model="recognizeText"
                type="textarea"
                placeholder="粘贴收件人信息（如：张三 13888888888 北京市朝阳区...）"
                rows="3"
              />
              <el-button class="ocr-btn" type="primary" @click="handleRecognize">识别</el-button>
            </div>
          </el-form-item> -->

          <!-- 客户信息 -->
          <el-row :gutter="12" class="customer-row">
            <el-col :span="11">
              <el-form-item label="客户姓名" prop="receiverName">
                <el-input v-model="form.receiverName" placeholder="请输入客户姓名">
                  <template #suffix>
                    <el-button type="primary" link @click="selectCustomerRef?.show()">
                      选择客户
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="choose-customer-col"> </el-col>
            <el-col :span="11">
              <el-form-item label="客户电话" prop="receiverPhone">
                <el-input v-model="form.receiverPhone" placeholder="请输入客户电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="收货地址" prop="receiverAddress">
            <el-input v-model="form.receiverAddress" type="textarea" placeholder="请输入收货地址" />
          </el-form-item>
        </template>
      </div>

      <!-- 产品明细 -->
      <div class="section-title">
        <span class="label">产品明细</span>

        <div class="product-header">
          <span class="product-title">
            <el-text v-if="!isEmpty(packageData)" type="success" size="large"
              >套餐名称: {{ packageData.productName }}
            </el-text>
          </span>
          <el-button :icon="Link" link type="primary" @click="selectPackage">从套餐选择</el-button>
          <span class="ml-10">
            <!-- 是否是固定套餐 用etag展示 1 是 0 否 -->
            <el-tag
              v-if="form.isFixed"
              closable
              @close="fixedClose"
              type="success"
              effect="dark"
              size="small"
              >固定套餐</el-tag
            >
            <el-tag v-else type="warning" effect="dark" size="small">普通</el-tag>
          </span>
        </div>

        <el-table style="margin-top: 10px" :data="form.productCollection" border size="small">
          <el-table-column label="产品名称" prop="productName" />
          <el-table-column
            label="产品类型"
            prop="usageType"
            width="110"
            :formatter="getGoodsTypeByUsageType"
          >
          </el-table-column>
          <el-table-column label="赠品" prop="isGift" width="60">
            <template #default="{ row }">
              <span>{{ row.isGift === 1 ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="件数" width="150">
            <template #default="{ row }">
              <el-input-number
                v-if="!form.isFixed"
                v-model="row.num"
                style="width: 100%"
                controls-position="right"
                :min="0"
              />
              <span v-else> {{ row.num }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="成本价" width="80" prop="costPrice" /> -->
          <el-table-column label="销售价" width="150" prop="productPrice">
            <template #default="{ row }">
              <el-input-number
                v-model="row.productPrice"
                style="width: 100%"
                controls-position="right"
                :min="0"
                v-if="!form.isFixed"
              />
              <span v-else> {{ row.productPrice }}</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="total-bar">
          <span
            >合计：<b>{{ totalQty }}</b> 件 &nbsp;
            <template v-if="isEmpty(packageData)">
              <b class="amount">{{ totalAmount }}</b>
            </template>
            <!-- 套餐价 -->
            <template v-else>
              <b class="amount oldSalePrice">原价：{{ totalAmount }}</b>
              <b class="salePrice">优惠价：{{ packageData.salePrice }}</b>
            </template>
            元</span
          >
        </div>
      </div>

      <!-- 付款方式 -->
      <div class="section-title">
        <span class="label">付款方式</span>
        <el-form-item label="付款方式" prop="paymentMethod">
          <el-radio-group v-model="form.paymentMethod" :disabled="form.relatedOrderId !== ''">
            <el-radio v-for="item in props.payType" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="已付金额" prop="actualPrice">
              <el-input-number
                v-model="form.actualPrice"
                controls-position="right"
                style="width: 100%"
                @change="handleActualAmount"
                :min="0"
              >
                <template #suffix>
                  <span>RMB</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="代收金额" prop="codAmount">
              <el-input-number
                v-model="form.codAmount"
                controls-position="right"
                style="width: 100%"
                @change="handleTotalAmount"
                :min="0"
              >
                <template #suffix>
                  <span>RMB</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input-number
                v-model="form.totalAmount"
                controls-position="right"
                style="width: 100%"
                disabled
                :min="0"
              >
                <template #suffix>
                  <span>RMB</span>
                </template>
              </el-input-number>
              <div v-if="form.transferOrderAmount" class="transfer-order-amount">
                <el-alert
                  class="alert"
                  :closable="false"
                  type="success"
                  :title="`转定金金额￥${form.transferOrderAmount}`"
                ></el-alert>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物流类型" prop="shippingType">
              <!-- 单选 自主发货 和 系统物流 -->
              <el-radio-group v-model="form.shippingType" @change="shippingChange">
                <el-radio
                  v-for="item in logisticsTypeOptions"
                  :label="item.value"
                  :key="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="延期发货" prop="isDelayedDelivery">
              <el-radio-group v-model="form.isDelayedDelivery">
                <el-radio :value="0">否</el-radio>
                <el-radio :value="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <template v-if="form.shippingType == '1'">
            <el-col :span="12">
              <el-form-item label="物流公司" prop="logisticsPlatformCode">
                <el-select
                  v-model="form.logisticsPlatformCode"
                  placeholder="请选择"
                  :options="logisticsCompany"
                />
              </el-form-item>
            </el-col>
          </template>
          <!-- 自主发货的时候 才需要写死物流 -->
          <template v-else>
            <el-col :span="12">
              <el-form-item label="三方物流" prop="logisticsPlatformCode">
                <el-select
                  v-model="form.logisticsPlatformCode"
                  placeholder="请选择补单物流"
                  :options="sysSelfFulfillmentOgistics"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物流单号" prop="logisticsNo">
                <el-input
                  v-model="form.logisticsNo"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入补单物流单号"
                  type="text"
                />
              </el-form-item>
            </el-col>
          </template>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="订单时间" prop="orderTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.orderTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                disabled
                type="datetime"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="订单来源" prop="channelType">
              <el-select v-model="form.channelType" placeholder="请选择">
                <el-option
                  v-for="item in orderFrom"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上传附件" prop="fileAttachment">
              <ImageUpload
                v-model="form.fileAttachment"
                action="/common/upload"
                class="upload-box"
                :limit="1"
                :file-type="['png', 'jpg', 'jpeg']"
                :is-show-tip="true"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否大单" prop="isBigOrder">
              <el-radio-group v-model="form.isBigOrder">
                <el-radio v-for="item in isBigOrderOptions" :key="item.value" :value="item.value">{{
                  item.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-form-item label="订单备注" prop="orderRemark">
          <el-input v-model="form.orderRemark" type="textarea" rows="3" placeholder="请输入备注" />
        </el-form-item>
      </div>
    </el-form>

    <!-- footer -->
    <template #footer>
      <div class="footer-btns">
        <el-button @click="hide" :disabled="loading">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">提交订单</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 客户选择弹窗 -->
  <SelectCustomer ref="selectCustomerRef" @select="selectCustomer" />
  <!-- 商品选择弹窗 -->
  <SelectGoodsPackage ref="selectGoodsPackageRef" @ok="selectGoodsPackage" />
  <!-- 选择平台订单 -->
  <orderSelectionDialog
    ref="orderDialogRef"
    type="1"
    :goodsTypes="goodsTypes"
    @select="handleOrderSelect"
  />
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue';
import { dayjs, ElMessage } from 'element-plus';
import { ArrowDown, ArrowUp, Link, Search } from '@element-plus/icons-vue';
import {
  addRepeatPurchaseAppendOrder,
  addRepeatPurchaseOrder
} from '../../api/platformOrders/orders/repeatPurchaseOrder';
import { isBigOrderOptions } from '../../utils/golbalData';
import { cloneDeep, isEmpty } from 'lodash';
import { ElLoading } from 'element-plus';

const orderDialogRef = ref();
const visible = ref(false);
const recognizeText = ref('');
const title = ref<string>(); // 标题
const addType = ref<string>(); // 操作类型
// 修改为props接收
interface Option {
  value?: any;
  label?: string;
  [key: string]: any;
}
const props = withDefaults(
  defineProps<{
    logisticsCompany?: Option[];
    payType?: Option[];
    goodsTypes?: Option[];
    goodsList?: Option[];
    orderFrom?: Option[];
    logisticsTypeOptions?: Option[];
    sysSelfFulfillmentOgistics?: Option[];
  }>(),
  {
    // 物流公司
    logisticsCompany: () => [],
    // 支付方式
    payType: () => [],
    // 商品类型
    goodsTypes: () => [],
    // 基础商品列表
    goodsList: () => [],
    // 订单来源
    orderFrom: () => [],
    // 发货类型
    logisticsTypeOptions: () => [],
    // 系统自提物流公司
    sysSelfFulfillmentOgistics: () => []
  }
);

const formRef = ref<any>();

// 初始化表单字段
const initField = () => ({
  relatedOrderId: '', // 追加的原始单，不填则表示不是追加单
  orderPrice: '',
  orderNo: '',
  orderSource: '',
  receiverName: '',
  receiverPhone: '',
  receiverAddress: '',
  customerId: '',
  productCollection: [] as any,
  paymentMethod: '',
  channelType: '',
  totalAmount: 0,
  actualPrice: 0,
  transferOrderAmount: 0,
  codAmount: 0,
  isDelayedDelivery: 0,
  expressCompany: '',
  fileAttachment: '',
  expressNo: '',
  orderTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  isBigOrder: 0,
  orderRemark: '',
  logisticsPlatformCode: '',
  logisticsNo: '',
  shippingType: '1',
  // 是否是固定套餐商品 1-是 0-否
  isFixed: 0
});

const form = reactive(initField());
const isCollapsed = ref(false);
const loading = ref(false);

const selectCustomerRef = ref();
const selectGoodsPackageRef = ref();
const emits = defineEmits(['ok']);

const rules: any = computed(() => {
  const rulesData: any = {
    receiverName: [{ required: true, message: '请输入姓名', trigger: 'change' }],
    receiverPhone: [{ required: true, message: '请输入电话', trigger: 'change' }],
    receiverAddress: [{ required: true, message: '请输入地址', trigger: 'change' }],
    isBigOrder: [{ required: true, message: '请选择是否大单', trigger: 'change' }],
    paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
    logisticsPlatformCode: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
    orderRemark: [
      {
        required: true,
        message: '请填写备注',
        trigger: 'change'
      }
    ]
  };

  // 如果是转换订单，附件必传
  if (form.relatedOrderId) {
    rulesData.fileAttachment = [
      {
        required: true,
        message: '请上传附件',
        trigger: 'change'
      }
    ];
  }

  return rulesData;
});

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 根据产品类型
const getGoodsTypeByUsageType = (row: any) => {
  const type = row.usageType;
  const findx: any = props.goodsTypes.filter((item: any) => item.value === type);
  if (findx.length > 0) {
    return findx[0].label;
  }
  return '';
};

// 固定套餐商品关闭
const fixedClose = () => {
  packageData.value = {};
  form.isFixed = 0;
  const list = cloneDeep(props.goodsList);
  list.forEach((v) => {
    v.num = 0;
  });
  // 初始化套餐列表
  form.productCollection = list;
};

// 合计多少件
const totalQty = computed(() =>
  form.productCollection.reduce((t: number, p: any) => t + (p.num || 0), 0)
);

// 合计金额
const totalAmount = computed(() => {
  return form.productCollection.reduce(
    (t: number, p: any) => t + (p.num || 0) * (p.productPrice || 0),
    0
  );
});

// 代收金额不能超过总金额 - 已付金额
const handleTotalAmount = () => {
  // 最多待收金额
  const maxDs = (form.totalAmount || 0) - (form.actualPrice || 0);
  if (form.codAmount > maxDs) {
    form.codAmount = Math.min(form.codAmount, maxDs);
    ElMessage.warning('代收金额不能超过总金额 - 已付金额');
    return;
  }
};

// 已收金额不能超过 总金额 - 代付金额
const handleActualAmount = () => {
  // 最多已收金额
  const maxYs = (form.totalAmount || 0) - (form.codAmount || 0);
  if (form.actualPrice > maxYs) {
    const totalPrice = Math.min(form.actualPrice, maxYs); // 限制总价
    // const remainingPayment = totalPrice - form.transferOrderAmount; // 剩余要付的钱
    // 已付金额不能超过总金额 - 代收金额 - 转单金额
    form.actualPrice = totalPrice;
    return;
  }
};

// 合计金额变动 修改总价
watch(totalAmount, (newVal) => {
  if (packageData.value.isFixed) {
    return (form.totalAmount = packageData.value.salePrice);
  }
  form.totalAmount = newVal;
});

// 从套餐选择
function selectPackage() {
  selectGoodsPackageRef.value.show();
}

// 选择套餐
const packageData = ref({});
function selectGoodsPackage(goods: any) {
  packageData.value = goods;
  form.isFixed = goods.isFixed;
  // 判断商品是否固定
  // 同步数量和价格到商品列表
  goods.productCollection.forEach((item: any) => {
    item.productPrice = item.salePrice; // 这里一定要用销售价
  });
  form.productCollection = goods.productCollection;
}

// 选择订单
const handleOrderSelect = (row: any) => {
  form.relatedOrderId = row.orderId;
  form.orderPrice = row.orderPrice;
  // 转订单金额
  form.transferOrderAmount = row.actualPrice;
  // form.totalAmount = row.totalAmount;
  form.receiverName = row.receiverName;
  form.receiverPhone = row.receiverPhone;
  form.receiverAddress = row.receiverAddress;
  form.orderTime = row.orderTime;
  // 平台转换复购
  form.paymentMethod = '5';
  form.orderRemark = `复购订单${row.orderNo} 转换定金额为：${row.actualPrice}`;
};

const customerDialogVisible = ref(false);

function selectCustomer(row: any) {
  form.receiverName = row.customerName;
  form.receiverPhone = row.customerPhone;
  form.receiverAddress = row.contactAddress;
  form.customerId = row.customerId;
  customerDialogVisible.value = false;
}

// 提交订单
function handleSubmit() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 空包裹验证
      if (totalQty.value == 0) {
        ElMessage.warning('不能创建空订单');
        return;
      }

      // 验证 金额 不为零cer
      if (form.totalAmount == 0) {
        ElMessage.warning('订单金额不能为零');
        return;
      }
      console.log('form ==>  ', form);
      // 已付 + 代付 = 总金额
      if ((form.actualPrice || 0) + (form.codAmount || 0) != form.totalAmount) {
        ElMessage.warning('已付、代付金额的和与总金额不一致');
        return;
      }

      // 设置为全屏loading
      loading.value = true;
      const loadings = ElLoading.service({
        lock: true,
        text: '复购单创建中...',
        background: 'rgba(255, 255, 255, 0.7)'
      });

      let fun;
      // 判断是否是追加订单
      if (form.relatedOrderId) {
        fun = addRepeatPurchaseAppendOrder;
      } else {
        // 普通复购订单
        fun = addRepeatPurchaseOrder;
      }

      // 过滤掉 form.productCollection 中 num = 0 的 商品
      form.productCollection = form.productCollection.filter((item: any) => item.num > 0);

      fun(form)
        .then((res: any) => {
          loading.value = false;
          if (res.code === 200) {
            ElMessage.success('添加成功');
            visible.value = false;
            loadings.close();
            packageData.value = {};
            formRef.value?.resetFields();
            emits('ok');
          }
        })
        .catch(() => {
          loading.value = false;
          loadings.close();
        });
    }
  });
}

// 初始化form 字段
const resetForm = () => {
  // 初始化商品列表
  formRef.value?.resetFields();
  Object.assign(form, initField());
  form.productCollection = cloneDeep(props.goodsList);
};

// type = superaddition 表示是追加复购单
const show = async (type: string, data: any) => {
  visible.value = true;
  addType.value = type;
  resetForm();
  if (type === 'superaddition') {
    title.value = '追加复购单';
  } else if (type === 'edit') {
    title.value = '编辑复购单';
    // 数字转换字符串
    data.shippingType += '';
    nextTick(() => {
      Object.assign(form, data);
    });
  } else {
    title.value = '添加复购单';
  }
};

// 监听物流类型 清空物流和单号
const shippingChange = () => {
  form.logisticsPlatformCode = '';
  form.logisticsNo = '';
};

// 监听商品列表变化，更新订单商品列表
watch(
  () => props.goodsList,
  (newVal: any) => {
    if (!newVal) return;

    form.productCollection = newVal.map((v: any) => ({
      ...v,
      num: 0
    }));
  },
  { immediate: true }
);

// 关闭弹窗
const hide = () => {
  visible.value = false;
  resetForm();
};

defineExpose({
  show,
  hide
});
</script>

<style scoped lang="scss">
.order-form {
  .section-title {
    border: 1px solid #ebebeb;
    padding: 40px 20px 20px 20px;
    box-sizing: border-box;
    border-radius: 4px;
    position: relative;
    margin-bottom: 10px;

    .label {
      position: absolute;
      display: inline-block;
      padding: 5px 10px;
      background: #ebebeb;
      font-size: 13px;
      margin-bottom: 10px;
      border-radius: 0 4px 4px 0;
      left: 0;
      top: 0;
    }

    .collapse-btn {
      padding: 0;
      left: auto;
      right: 0;
      border: 1px solid #ebebeb;
    }
  }
}

.transfer-order-amount {
  position: relative;
  width: 100%;

  .alert {
    position: absolute;
    left: 0;
    width: 100%;
    padding: 1px 10px;
  }
}

.recognize-row {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  width: 100%;
  position: relative;

  .ocr-input {
    box-sizing: border-box;
  }

  .ocr-btn {
    position: absolute;
    bottom: 8px;
    right: 16px;
  }
}

.customer-row .choose-customer-col {
  display: flex;
  align-items: center;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: absolute;
  right: 20px;
  top: 10px;
}

.product-title {
  margin-right: 50px;
  font-weight: bold;
}

.total-bar {
  text-align: right;
  font-size: 15px;
  font-weight: 500;
  color: #333;
  padding-top: 8px;
  padding-right: 8px;
}

.total-bar {
  .amount {
    color: #f56c6c;
    font-weight: 700;
  }

  .oldSalePrice {
    text-decoration: line-through;
  }

  .salePrice {
    margin-left: 10px;
  }
}

.footer-btns {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
